package commands

import (
	"fmt"
	"time"

	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/vehicle_brand"
	"gitee.com/sweetsunnyflower/carpooling-server-go/app/models/vehicle_model"

	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/console"
	"gitee.com/sweetsunnyflower/carpooling-server-go/pkg/logger"

	"net/http"

	"github.com/spf13/cast"
	"github.com/spf13/cobra"

	"github.com/PuerkitoBio/goquery"
)

var CmdSyncVehicleBrand = &cobra.Command{
	Use:   "sync_vehicle_brand",
	Short: "爬取懂车帝车型",
	Run:   runSyncVehicleBrand,
	Args:  cobra.ExactArgs(2),
}

func runSyncVehicleBrand(cmd *cobra.Command, args []string) {

	for i := cast.ToInt(args[0]); i < cast.ToInt(args[1]); i++ {
		syncBrand(i)
		if i%3 == 0 {
			time.Sleep(time.Second * 1)
		}
	}
}

func syncBrand(id int) {
	// Request the HTML page.
	res, err := http.Get("https://www.dongchedi.com/auto/series/" + cast.ToString(id))
	if err != nil {
		console.Error(err.Error())
	}
	defer res.Body.Close()

	if res.StatusCode != 200 {
		console.Error("请求响应错误")
		logger.ErrorJSON("请求响应错误", "response", map[string]interface{}{
			"res.StatusCode": res.StatusCode,
			"res.Status":     res.Status,
		})
	}

	// Load the HTML document
	doc, err := goquery.NewDocumentFromReader(res.Body)
	if err != nil {
		console.Error(err.Error())
	}

	var brandId uint64 = 0

	fmt.Println(len(doc.Find(".icon-arrow-ic-r").Nodes))

	doc.Find(".icon-arrow-ic-r").Each(func(i int, s *goquery.Selection) {

		if s.Text() != "" {

			if i == 0 {
				logger.InfoString("获取品牌", "品牌ID", s.Text())
				brand := vehicle_brand.GetByName(s.Text())

				if brand.ID == 0 {
					newBrand := &vehicle_brand.VehicleBrand{
						Name:    s.Text(),
						QueryId: cast.ToUint64(id),
					}
					newBrand.Create()
					brand = *newBrand
				}

				brandId = brand.ID
			}

			if i == 1 && brandId != 0 {
				logger.InfoString("获取型号", "型号ID", s.Text())
				model := vehicle_model.GetByName(s.Text())

				if model.ID == 0 {
					newModel := vehicle_model.VehicleModel{
						Name:    s.Text(),
						BrandId: brandId,
					}
					newModel.Create()
				}

			}
		}

	})
}
